import { useRef, useState } from "react";
class FormStore {
    constructor(forceUpdate) {
        this.store = {};
        this.callbacks = {};
        this.forceUpdate = forceUpdate;
        this.fieldEntities = [];
    }
    registerField = (entity) => {
        this.fieldEntities.push(entity);
    }
    getFieldValue = (key) => {
        return this.store[key];
    }
    setFieldValue = (key, value) => {
        this.store[key] = value;
        this.fieldEntities.forEach((item) => item.onStoreChange());
    }
    setCallbacks = (callbacks) => {
        this.callbacks = callbacks;
    }
    submit = () => {
        this.callbacks.onFinish(this.store);
    }
    setInitialValue = (initialStore) => {
        this.store = initialStore;
    }
    getForm() {
        return {
            getFieldValue: this.getFieldValue,
            setFieldValue: this.setFieldValue,
            setCallbacks: this.setCallbacks,
            submit: this.submit,
            forceUpdate: this.forceUpdate,
            setInitialValue: this.setInitialValue,
            registerField: this.registerField,
        };
    }
}


const useForm = () => {
    const formRef = useRef();
    const [, forceUpdate] = useState({});
    if (!formRef.current) {
        const formStore = new FormStore(forceUpdate);

        formRef.current = formStore.getForm();
    }
    return [formRef.current];
};

export default useForm;
